import { IHanderResponse, IWorkerImpl } from "db://xworker/WokerTypes"
import * as WebAPI from './server/start';

export function getWorkerImplUrl (): string {
  return import.meta.url
}

export default class WorkerImpl implements IWorkerImpl<string> {
  initWorker (self: Worker, context: any, data?:any): void {
    WebAPI.initData(data, '', 0)
  }

  handleWork (context: any, cmd: string, data: any): Promise<IHanderResponse<string>> {
    console.log('handleWork >>>>>>>>>>>>>>>>>>> ', JSON.stringify(data))
    return new Promise<IHanderResponse<string>>((resolve, reject) => {
      const func = (WebAPI as any)[cmd] as (params: string, user: string)=>string
      if (!func) {
        reject(`No func named ${cmd}`)
      } else {
        const result = func(data.params, data.userData)
        const resp: IHanderResponse<string> = {
          isResponse: true,
          data: result
        }
        resolve(resp)
      }
    })
  }
}